﻿# 
# 以下代码仅供参考。
# 
'''
问题1:数据统计。要求:修改PY301-1. py文件中代码，分别统计两个文件中出现次数最多的10词语，作为主题
词，要求词语不少于2个字符，打印输出在屏幕上，输出示例如下: (示例词语非答案 )
2019:改革:10,企业:9, .. (略),深化:2
2018:改革:11,效益:7, .. (略),深化:1
注意:输出格式采用英文冒号和英文逗号，标点符号前后无空格，各词语间用逗号分隔，最后一个词语后无逗
号。
'''

import jieba


def fun(txt):
    fp = open(txt)
    res = fp.read()
    words = jieba.lcut(res)
    # print(words)
    d = {}
    for word in words:
        if len(word) >= 2:
            d[word] = d.get(word, 0) + 1
    lt = list(d.items())
    lt.sort(key=lambda x: x[1], reverse=True)
    # 获取参数的年份
    tmp = txt[txt.find('2'):txt.find('.')] + ':'

    # 输出结果
    for i in range(10):
        tmp += '{}:{},'.format(lt[i][0], lt[i][-1])
    print(tmp[:-1])

    fp.close()


def fun1():
    fa = open("data2019.txt", "r")
    txt = fa.read()
    fa.close()
    words = jieba.lcut(txt)

    d = {}
    for word in words:
        if len(word) == 1:
            continue
        else:
            d[word] = d.get(word, 0) + 1

    lt = list(d.items())
    lt.sort(key=lambda x: x[1], reverse=True)
    # return lt  # 返回结果用来判断是否与自己的答案一样
    print("2019:", end="")
    for i in range(10):
        word, count = lt[i]
        if i < 9:
            print("{}:{}".format(word, count), end=",")
        else:
            print("{}:{}".format(word, count))


def fun2():
    fa = open("data2018.txt", "r")
    txt = fa.read()
    fa.close()
    words = jieba.lcut(txt)

    d = {}
    for word in words:
        if len(word) == 1:
            continue
        else:
            d[word] = d.get(word, 0) + 1

    lt = list(d.items())
    lt.sort(key=lambda x: x[1], reverse=True)
    # return lt  # 返回结果用来判断是否与自己的答案一样
    print("2018:", end="")
    for i in range(10):
        word, count = lt[i]
        if i < 9:
            print("{}:{}".format(word, count), end=",")
        else:
            print("{}:{}".format(word, count))


if __name__ == '__main__':
    fun('data2019.txt')
    fun('data2018.txt')

    # print(fun1() == fun('data2019.txt'))
    # print(fun2() == fun('data2018.txt'))
